package com.googlecode.cswish.security.type;

import com.googlecode.cswish.security.Context;
import com.googlecode.cswish.util.FreemarkerTemplateEngine;

import freemarker.template.SimpleHash;

/**
 * Rule is a freemarker template
 * 
 * @author Jerry.Feng Date: 2008-6-10
 */
public class FreemarkerRule implements PermissionRule {

	private String name;
	
	private String condition;
	
	@Override
	public void setCondition(String condition) {
		this.condition = condition;
	}

	@Override
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * condition == true, means the limit is valid, user has the permission to visit it.
	 */
	@Override
	public String execute(Context context) {
		String value = null;
		if (context != null) {
			FreemarkerTemplateEngine engine = FreemarkerTemplateEngine.getInstance();
			engine.register(name, condition);
			
			SimpleHash model = context.toTemplateModel();
			value = engine.execute(condition, model);
		}
		return value;
	}

	@Override
	public boolean executeBoolean(Context context) {
		return Boolean.valueOf(execute(context));
	}
}